<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2019/4/19
 * Time: 15:57
 */
namespace app\admin\controller;
use think\Db;
use think\Request;

class Shop extends Base {
    public function index(){
        if(request()->isAjax()){
            $where = array();
            $params = input('param.');
            $where['coupon_status'] = array('NEQ',3);
            if(isset($params['coupon_status']) && $params['coupon_status'] != '')
            {
                $where['coupon_status'] = $params['coupon_status'];
            }
            if(isset($params['key']) && $params['key'] != '')
            {
                $where['coupon_name'] = ['like', "%" . $params['key'] . "%"];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('coupon')->alias('a')
                ->join('up_supplier us','us.supplier_id = a.f_id','left')
                ->where($where)->count();// 获取总条数
            $lists = Db::name('coupon')->alias('a')
                ->where($where)
                ->join('up_supplier us','us.supplier_id = a.f_id','left')
                ->order('coupon_time desc')
                ->page($Nowpage,$limits)
                ->field('a.*,us.supplier_name')
                ->select();
            foreach ($lists as $key=>&$vo){
                $vo['time'] = date('Y-m-d H:i',strtotime($vo['coupon_start'])).' 至 '.date('Y-m-d H:i',strtotime($vo['coupon_end']));
                $vo['time1'] = date('Y-m-d H:i',strtotime($vo['coupon_use_start'])).' 至 '.date('Y-m-d H:i',strtotime($vo['coupon_use_end']));
                $nownum = Db::name('coupon_children')
                    ->where('f_id',$vo['coupon_id'])
                    ->where('coupon_children_type','in','1,2')
                    ->count();
                $nownum2 = Db::name('coupon_children')
                    ->where('f_id',$vo['coupon_id'])
                    ->where('coupon_children_type',1)
                    ->count();
                $lists[$key]['coupon_num'] = $nownum;
                Db::name('coupon')->where('coupon_id',$vo['coupon_id'])->setField('coupon_num',$nownum2);
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        if(session('?coupon_id')){
            session('coupon_id',null);
        }
        return $this->fetch();
    }


    //删除
    public function del(){
        $id = input('param.id');
        $where['coupon_id'] = $id;
        $info = Db::table('up_coupon')->where($where)->find();
        if($info['coupon_status']==1){
            return json(['code'=>100,'msg'=>'不能删除上架的优惠券，请先下架优惠券']);
        }
        $data['coupon_status'] =3;
        $res = Db::table('up_coupon')->where($where)->update($data);
        if($res){
            return json(['code'=>200,'msg'=>'删除成功']);
        }else{
            return json(['code'=>100,'msg'=>'删除失败']);
        }
    }

    //上架
    public function upper(){
        $id = input('param.id');
        $where['coupon_id'] = $id;
//        $info = Db::table('up_coupon')->where($where)->find();
//        if($info['coupon_status']==1){
//            return json(['code'=>100,'msg'=>'不能删除上架的优惠券，请先下架优惠券']);
//        }
        $data['coupon_status'] =1;
        $res = Db::table('up_coupon')->where($where)->update($data);
        if($res){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>100,'msg'=>'操作失败']);
        }
    }
    //下架
    public function lower(){
        $id = input('param.id');
        $where['coupon_id'] = $id;
//        $info = Db::table('up_coupon')->where($where)->find();
//        if($info['coupon_status']==1){
//            return json(['code'=>100,'msg'=>'不能删除上架的优惠券，请先下架优惠券']);
//        }
        $data['coupon_status'] =2;
        $res = Db::table('up_coupon')->where($where)->update($data);
        if($res){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>100,'msg'=>'操作失败']);
        }
    }
    public function couponAdd(){
        if(Request::instance()->isPost()){
            $params = input('param.');
            if((int)$params['coupon_price'] <= 0){
                return json(['code' => 100, 'msg' => '价格不能低于0']);
            }
            $data = [
//                'coupon_code' => trim($params['coupon_code'], ' '),//兑换码
                'coupon_name' => trim($params['coupon_name'], ' '),//优惠券名称
                'coupon_image' => $params['coupon_image'],//缩略图
                'coupon_num' => 0,//数量
                'coupon_price' => (int)$params['coupon_price'],//兑换价格
                'coupon_start' => $params['coupon_start'],//我能兑换的开始时间
                'coupon_end' => $params['coupon_end'],//我能兑换的结束时间
                'coupon_use_start' => $params['coupon_use_start'],//领取开始时间
                'coupon_use_end' => $params['coupon_use_end'],//领取结束时间
                'coupon_time' => date('Y-m-d H:i:s'),//添加时间
                'f_id' => $params['f_id']//添加时间
            ];
            $res = Db::table('up_coupon')->insert($data);
            if($res){
                return json(['code' => 200, 'msg' => '添加成功']);
            }else{
                return json(['code' => 100, 'msg' => '添加失败']);
            }
        }
        $realm = Db::table('up_supplier')->select();
        $this->assign('realm',$realm);
        return $this->fetch('shop/couponadd');
    }
    /***
     * @return mixed|\think\response\Json
     * 编辑
     */
    public function update(){
        if(Request::instance()->isPost()){
            $params = input('param.');
            if(!empty($params['coupon_image'])){
                $data['coupon_image'] = $params['coupon_image'];
            }
            if((int)$params['coupon_price'] <= 0){
                return json(['code' => 100, 'msg' => '价格不能低于0']);
            }
            $data = [
//                'coupon_code' => trim($params['coupon_code'], ' '),//兑换码
                'coupon_name' => trim($params['coupon_name'], ' '),//优惠券名称
                'coupon_image' => $params['coupon_image'],//缩略图
//                'coupon_num' => trim($params['coupon_num'], ' '),//数量
                'coupon_price' => (int)$params['coupon_price'],//兑换价格
                'coupon_start' => $params['coupon_start'],//我能兑换的开始时间
                'coupon_end' => $params['coupon_end'],//我能兑换的结束时间
                'coupon_use_start' => $params['coupon_use_start'],//领取开始时间
                'coupon_use_end' => $params['coupon_use_end'],//领取结束时间
            ];
            $res = Db::table('up_coupon')->where('coupon_id',$params['id'])->update($data);
            if($res){
                return json(['code' => 200, 'msg' => '添加成功']);
            }else{
                return json(['code' => 100, 'msg' => '添加失败']);
            }
        }
        $id= input('param.id');
        $data = Db::table('up_coupon')->where('coupon_id',$id)->find();
        $realm = Db::table('up_supplier')->select();
        $this->assign('realm',$realm);
        $this->assign('data',$data);
        $this->assign('id',$id);
        return $this->fetch();
    }

    //查看
    public function detail(){
        if(request()->isAjax()){
            $id = input('param.id');
            $where['f_id'] = $id;
            $where['coupon_children_type'] = array('neq',3);
            $info = Db::table('up_coupon')->where('coupon_id',$id)->find();
            $info['supplier_name'] = Db::table('up_supplier')->where('supplier_id',$info['f_id'])->value('supplier_name');
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('coupon_children')->alias('a')
                ->where($where)->count();// 获取总条数
            $lists = Db::name('coupon_children')->alias('a')
                ->where($where)
                ->page($Nowpage,$limits)
                ->select();
            foreach ($lists as $key=>&$vo){
                $vo['supplier_name'] = $info['supplier_name'];
                $vo['coupon_name'] = $info['coupon_name'];
                $vo['coupon_image'] = $info['coupon_image'];
                $vo['coupon_time'] = $info['coupon_time'];
                $vo['coupon_status'] = $info['coupon_status'];
                $vo['coupon_children_price'] = $info['coupon_price'];
                $vo['time'] = date('Y-m-d H:i',strtotime($info['coupon_start'])).' 至 '.date('Y-m-d H:i',strtotime($info['coupon_end']));
                $vo['time1'] = date('Y-m-d H:i',strtotime($info['coupon_use_start'])).' 至 '.date('Y-m-d H:i',strtotime($info['coupon_use_end']));
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        session('coupon_id',input('id'));
        $this->assign('id',input('id'));
        return $this->fetch();
    }

    /***
     * @return mixed|\think\response\Json
     * 添加兑换码
     */
    public function add(){
        if(Request::instance()->isPost()){
            $params = input('param.');
            $data = [
                'coupon_children_code' => trim($params['coupon_code'], ' '),//优惠券名称
//                'coupon_children_price' => $params['coupon_price'],//缩略图
                'create_time' => date('Y-m-d H:i:s'),//添加时间
                'f_id' => $params['id']//添加时间
            ];
            $res = Db::table('up_coupon_children')->insert($data);
            if($res){
                Db::table('up_coupon')->where('coupon_id',$params['id'])->setInc('coupon_num',1);
                return json(['code' => 200, 'msg' => '添加成功']);
            }else{
                return json(['code' => 100, 'msg' => '添加失败']);
            }
        }
        $this->assign('id',input('param.id'));
        return $this->fetch();
    }

    /***
     * @return mixed|\think\response\Json
     * 编辑
     *
     */
    public function edit(){
        if(Request::instance()->isPost()){
            $params = input('param.');
            $data = [
                'coupon_children_code' => trim($params['coupon_code'], ' '),//优惠券名称
//                'coupon_children_price' => $params['coupon_price'],//缩略图
            ];
            $res = Db::table('up_coupon_children')->where('coupon_children_id',$params['id'])->update($data);
            if($res){
                return json(['code' => 200, 'msg' => '添加成功']);
            }else{
                return json(['code' => 100, 'msg' => '添加失败']);
            }
        }
        $data = Db::table('up_coupon_children')->where('coupon_children_id',input('param.id'))->find();
        $this->assign('id',input('param.id'));
        $this->assign('data',$data);
        return $this->fetch();
    }
    //删除
    public function dels(){
        $id = input('param.id');
        $where['coupon_children_id'] = $id;
        $info = Db::table('up_coupon_children')->where($where)->find();
        if($info['coupon_children_type']==1){
            return json(['code'=>100,'msg'=>'不能删除上架的优惠券，请先下架优惠券']);
        }
        $data['coupon_children_type'] =3;
        $res = Db::table('up_coupon_children')->where($where)->update($data);
        if($res){
            Db::table('up_coupon')->where('coupon_id',$info['f_id'])->setDec('coupon_num',1);
            return json(['code'=>200,'msg'=>'删除成功']);
        }else{
            return json(['code'=>100,'msg'=>'删除失败']);
        }
    }

    //上架
    public function uppers(){
        $id = input('param.id');
        $where['coupon_children_id'] = $id;
        $info = Db::table('up_coupon_children')->where($where)->find();
        if($info['coupon_children_type']==1){
            return json(['code'=>100,'msg'=>'此优惠券已经上架']);
        }
        $data['coupon_children_type'] =1;
        $res = Db::table('up_coupon_children')->where($where)->update($data);
        if($res){
            Db::table('up_coupon')->where('coupon_id',$info['f_id'])->setInc('coupon_num',1);
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>100,'msg'=>'操作失败']);
        }
    }
    //下架
    public function lowers(){
        $id = input('param.id');
        $where['coupon_children_id'] = $id;
        $info = Db::table('up_coupon_children')->where($where)->find();
        if($info['coupon_children_type']==2){
            return json(['code'=>100,'msg'=>'此优惠券已经下架']);
        }
        $data['coupon_children_type'] =2;
        $res = Db::table('up_coupon_children')->where($where)->update($data);
        if($res){
            Db::table('up_coupon')->where('coupon_id',$info['f_id'])->setDec('coupon_num',1);
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>100,'msg'=>'操作失败']);
        }
    }

    /**
     * 导入Excel
     * @return mixed
     */
    public function excelIn()
    {
        if (request()->file('file')) {
            $file = request()->file('file');
            $info = $file->getInfo();
            $file_path = $info['tmp_name'];
            //取出文件后缀
            $file_type = explode(".", $info['name']);
            $file_type = end($file_type);
            vendor("PHPExcel.PHPExcel.IOFactory");
            if ($file_type == 'xls') {
                $inputFileType = 'Excel5';    //这个是读 xls的
            } else {
                $inputFileType = 'Excel2007';//这个是计xlsx的
            }
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($file_path);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
//            print_r($highestRow);die;
            for ($i = 2; $i <= $highestRow; $i++) {
                $a = $objPHPExcel->getActiveSheet()->getCell("A" . $i)->getValue();//获取A列的值
//                $b = $objPHPExcel->getActiveSheet ()->getCell ("B" . $i)->getValue ();//获取B列的值
                //插入学校
                if ($a) {
                    $data = [
                        'coupon_children_code' => $a,//优惠券名称
//                    'coupon_children_price' => $b,//缩略图
                        'create_time' => date('Y-m-d H:i:s'),//添加时间
                        'f_id' => session('coupon_id')//添加时间
                    ];
                    Db::table('up_coupon_children')->insertGetId($data);
                    Db::table('up_coupon')->where('coupon_id', session('coupon_id'))->setInc('coupon_num', 1);

                }
            }
            echo '/admin/shop/index';
        }
        return $this->fetch('shop/excelin');
    }
}